import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import {getInfo,cartList} from '@/api'
export default new Vuex.Store({
  // 存储数据源
  state: {
    // 已登录数据
    token:sessionStorage.getItem('token')?sessionStorage.getItem('token'):'',
    // 判断用户是否登录的状态
    isLogin:sessionStorage.getItem('isLogin')?sessionStorage.getItem('isLogin'):false,
    // 存储用户登录后的信息
    userInfo:null,
    // 购物车数据
    list:[],
    // 购物车商品数量对应的小红点
    badgeConst:0,
    // 购物车全选状态
    allChecked:true
  },
  getters:{
    getToken(state){
      return state.token
    },
    getIsLogin(state){
      return state.isLogin
    },
    getUserInfo(state){
      return state.userInfo
    },
    getBadgeConst(state){
      return state.badgeConst
    },
    // 计算购物车商品选中的价格
    getAllPrice(state){
      let countPrice = 0
      state.list.forEach((i)=>{
        if(i.checked){
          countPrice += i.count * i.price
        }
      })
      return countPrice
    }
  },
  mutations: {
    setToken(state,params){
      state.token = params.token
      sessionStorage.setItem('token',state.token)
      sessionStorage.setItem('isLogin',true)
      state.isLogin = true
    },
    setUserInfo(state,params){
      state.userInfo = params
    },
    setCartList(state,params){
      state.list = params
    },
    setBadgeConst(state,params){
      state.badgeConst = params
    },
    setAllChecked(state,params){
      state.allChecked = params
    }
  },
  actions: {
    getUserIfon(state){
      // 获取用户信息
      getInfo((res)=>{
        state.commit('setUserInfo',res.data)
      })
    },
    getCartList(state){
      // 获取购物车信息
      cartList((res)=>{
        const list = res.data
        if(res.status === 0){
          let count = 0
          list.forEach((i)=>{
            count += i.count
            i.checked = false
          })
          state.commit('setBadgeConst',count)
          state.commit('setCartList',list)
        }
      })
    },
    // 处理单选事件
    changeChecked(state){
      let checked = true
      state.state.list.forEach((item)=>{
        // 只要有一个单选的为false那么全部的也为false
        // 全部都为true时跳出判断
        if(!item.checked){
          checked = false
          return
        }
      })
      state.commit('setAllChecked',checked)
    },
    // 处理全部选中事件
    changeAllChecked(state){
      state.state.list.forEach((i)=>{
        // allChecked默认是为true去反为false遍历的i.checked也全部为false相反一个道理
        i.checked = !state.state.allChecked
      })
      state.commit('setAllChecked',!state.state.allChecked)
    }
  }
});
